<script>
export default {
  name: "uni-modal-button",
  props: {
    //弹窗标题
    modalTitle: {
      type: String,
      default: '提示'
    },
    //弹窗内容
    modalContent: {
      type: String,
      default: '是否确定继续操作？'
    },
    //弹窗确认按钮文字
    modalConfirmText: {
      type: String,
      default: '确定'
    },
    //弹窗取消按钮文字
    modalCancelText: {
      type: String,
      default: '取消'
    },
    //预检查函数
    validate: {
      type: Function,
      default: async () => true
    },
    //按钮类型
    type: {
      type: String,
      default: 'primary'
    },
    //按钮大小
    size: {
      type: String,
      default: 'normal'
    },
    //是否是朴素按钮
    plain: {
      type: Boolean,
      default: false
    },
    //弹窗是否带输入框
    modalEditable: {
      type: Boolean,
      default: false
    },
    //弹窗输入框提示文字
    modalPlaceholderText: {
      type: String,
      default: '请输入'
    }


  },
  methods: {
    //按钮点击事件
    async handleButtonClick() {
      try {
        await this.validate();
        this.showModal();
      } catch (e) {
        console.error(e);
      }
    },
    //显示弹窗
    showModal() {
      uni.showModal({
        title: this.modalTitle,
        content: this.modalEditable?'':this.modalContent,
        confirmText: this.modalConfirmText,
        cancelText: this.modalCancelText,
        editable: this.modalEditable,
        placeholderText: this.modalPlaceholderText,
        success: res => {
          if (res.confirm) {
            if (this.modalEditable) {
              if (res.content) {
                this.$emit('click', res.content);
              } else {
                uni.showToast({
                  title: this.modalPlaceholderText,
                  icon: 'none'
                });
              }
            } else {
              this.$emit('click');
            }
          }
        }
      });
    }
  }

}
</script>

<template>
  <u-button
      :type="type"
      :size="size"
      :plain="plain"
      @click="handleButtonClick">
    <slot></slot>
  </u-button>


</template>

<style scoped lang="scss">

</style>